package com.gc.web.controller.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.gc.business.domain.Attachment;
import com.gc.business.service.IAttachmentService;
import com.gc.common.base.AjaxResult;
import com.gc.common.config.Global;
import com.gc.common.constant.Constants;
import com.gc.common.utils.DateUtils;
import com.gc.common.utils.StringUtils;
import com.gc.common.utils.file.FileUtils;
import com.gc.common.utils.file.MimeTypeUtils;
import com.gc.framework.config.ServerConfig;
import com.gc.framework.util.FileUploadUtils;
import com.gc.framework.web.base.ApiBaseController;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysUserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 附件 api接口
 *
 * @author liujinteng
 * @date 2020-11-19
 */
@Controller
@RequestMapping("/api/attachment")
public class ApiAttachmentController extends ApiBaseController {

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysUserService userService;

    /**
     * 文件上传路径
     */
    public static final String UPLOAD_PATH = "/profile/upload/";

    /**
     * 删除附件接口
     *
     * @param attachId
     * @return
     */
    @PostMapping("/delAttachmentById")
    @ResponseBody
    public Map<String, Object> delAttachmentById(Long attachId) {
        if (StringUtils.isNull(attachId)) {
            return error(Constants.UNVERIFY, "缺少必传字段：id");
        }
        return success(attachmentService.removeById(attachId));
    }

    /**
     * 文件下载接口(返回原文件名)
     *
     * @param attachId
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/downloadFile")
    @ResponseBody
    public void downloadFile(Long attachId, HttpServletResponse response, HttpServletRequest request) {
        if (attachId == null) {
            Console.error(Constants.UNVERIFY, "参数错误:fileId有误");
        }
        // 查询文件源文件
        Attachment attachment = attachmentService.getById(attachId);
        if (attachment == null) {
            Console.error(Constants.UNVERIFY, "下载失败,文件不存在");
        }
        // 获取文件名称后缀
        String extension = FilenameUtils.getExtension(attachment.getAttachTitle());
        //替换文件路径前缀
        String downloadPath = Global.getProfile() + StringUtils.substringAfter(attachment.getAttachUrl(), "/profile");
        // 查询文件源文件
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, attachment.getAttachTitle()));
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通用单个附件上传接口
     */
    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(MultipartFile file, String token, Integer type) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNull(file)) {
            return error(Constants.UNVERIFY, "请先完成上传步骤！");
        }
        try {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;
            // 获取原文件名称
            String originalFileName = file.getOriginalFilename();
            // 获取文件名称后缀
            String extension = FileUploadUtils.getExtension(file);
            // 校验是否为图片类型
            boolean flag = FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.IMAGE_EXTENSION);
            Attachment attachment = new Attachment();
            attachment.setIsImg(flag ? 0 : 1);
            attachment.setIconUrl(FileUploadUtils.checkAttachSaveIcon(extension));
            attachment.setAttachUrl(url);
            String attachSize = FileUtils.convertFileSize(file.getSize());
            attachment.setAttachSize(attachSize);
            attachment.setAttachTitle(originalFileName);
            attachment.setCreateTime(DateUtil.date());
            SysUser user = userService.selectUserById(getUserId(token));
            attachment.setCreateBy(user.getUserName());
            attachmentService.save(attachment);
            map.put("originalFileName", originalFileName);
            map.put("fileName", fileName);
            map.put("url", url);
            map.put("location", url);
            map.put("relative_url", UPLOAD_PATH + fileName);
            map.put("attachment", attachment);
            map.put("type", type);
            return success(map);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用多个附件上传接口
     */
    @PostMapping("/uploadMore")
    @ResponseBody
    public Map<String, Object> uploadMore(HttpServletRequest request, String token) {
        Map<String, Object> map = new HashMap<>();


        // 上传文件路径
        String filePath = Global.getUploadPath();
        StringBuilder sb = new StringBuilder();

        String urlString = "";
        SysUser user = userService.selectUserById(getUserId(token));
        try {

            for (int i = 0; i < 99; i++) {

                // 检测是否为上传请求
                String contentType = request.getContentType();
                MultipartFile file = null;
                if (contentType != null && contentType.toLowerCase().startsWith("multipart/")) {
                    MultipartHttpServletRequest multipartRequest =
                            WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);

                    file = multipartRequest.getFile("file"+i);
                }

                if(file == null){
                    break;
                }

                Console.log("files{}", file);
                // 获取原文件名称
                String originalFileName = file.getOriginalFilename();
                Console.log("originalFileName{}", originalFileName);


                Attachment attachment = new Attachment();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;

                // 获取文件名称后缀
                String extension = FileUploadUtils.getExtension(file);
                // 校验是否为文档类型
                boolean flag = FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.IMAGE_EXTENSION);
                attachment.setIsImg(flag ? 0 : 1);
                attachment.setIconUrl(FileUploadUtils.checkAttachSaveIcon(extension));
                attachment.setAttachUrl(url);
                attachment.setAttachTitle(originalFileName);
                String attachSize = FileUtils.convertFileSize(file.getSize());
                attachment.setAttachSize(attachSize);
                attachment.setCreateTime(DateUtil.date());
                attachment.setCreateBy(user.getUserName());
                attachmentService.save(attachment);
                sb.append(attachment.getAttachUrl() + ",");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        urlString = sb.toString();
        urlString =  urlString.substring(0, urlString.length() -1);

        map.put("url", urlString);
        return success(map);
    }


    private static void assertIsMultipartRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        if (contentType == null || !contentType.toLowerCase().startsWith("multipart/")) {
            throw new MultipartException("The current request is not a multipart request");
        }
    }


}
